package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbProdImageMapper;
import com.bwie.pojo.TbProd;
import com.bwie.pojo.TbProdImage;
import com.bwie.service.TbProdService;
import com.bwie.mapper.TbProdMapper;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.Result;
import com.bwie.vo.AttaVo;
import com.bwie.vo.ProdPageVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* @author 39304
* @description 针对表【tb_prod(商品表)】的数据库操作Service实现
* @createDate 2025-05-27 15:37:47
*/
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class TbProdServiceImpl extends ServiceImpl<TbProdMapper, TbProd>
    implements TbProdService{
    @Autowired
    TbProdMapper tbProdMapper;

    @Autowired
    TbProdImageMapper tbProdImageMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Result getProdList(ProdPageVo prodPageVo) {
        Page<TbProd> page = new Page<>(prodPageVo.getPageNum(), prodPageVo.getPageSize());

//        QueryWrapper<TbProd> wrapper = new QueryWrapper<>();
//        wrapper.lambda().orderByDesc(TbProd::getCreateTime);
//        Page<TbProd> tbProdPage = tbProdMapper.selectPage(page, wrapper);

        Page<TbProd> tbProdPage = tbProdMapper.getProdList(page,prodPageVo);

        return Result.ok().setData(tbProdPage);
    }

    @Override
    public Result addProd(TbProd tbProd) {
        TbProd prod = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdSpu, tbProd.getProdSpu())
        );
        if (prod != null){
            return Result.error().setMsg("SPU商品已存在");
        }

        prod = tbProdMapper.selectOne(
                new QueryWrapper<TbProd>().lambda().eq(TbProd::getProdName, tbProd.getProdName())
        );
        if (prod != null){
            return Result.error().setMsg("商品已存在");
        }

        tbProd.setProdStatus(0);
        tbProd.setCreateBy("admin");
        tbProd.setCreateTime(new Date());
        tbProdMapper.insert(tbProd);

        return Result.ok();
    }

    @Override
    public Result deleteProdAll(List<TbProd> prodList) {
        for (TbProd tbProd : prodList) {
            tbProdMapper.deleteById(tbProd.getProdId());
        }
        return Result.ok();
    }

    @Override
    public Result addProdAtta(AttaVo attaVo) {
        TbProd tbProd = tbProdMapper.selectById(attaVo.getProdId());
        if (attaVo == null){
            return Result.error().setMsg("商品不存在");
        }

        tbProd.setProdVideo(attaVo.getProdVideo());
        tbProd.setUpType(attaVo.getUpType());
        tbProd.setUpTime(attaVo.getUpTime());
        tbProd.setDownType(attaVo.getDownType());
        tbProd.setDownTime(attaVo.getDownTime());
        tbProdMapper.updateById(tbProd);

        tbProdImageMapper.delete(new QueryWrapper<TbProdImage>().lambda().eq(TbProdImage::getProdId,tbProd.getProdId()));

        if (attaVo.getImageList() != null && attaVo.getImageList().size() > 0){
            for (String imageUrl : attaVo.getImageList()) {
                TbProdImage tbProdImage = new TbProdImage();
                tbProdImage.setProdId(tbProd.getProdId());
                tbProdImage.setImageUrl(imageUrl);

                tbProdImageMapper.insert(tbProdImage);
            }
        }

        return Result.ok();
    }

    @Override
    public Result checkProd(TbProd tbProd) {
        TbProd prod = tbProdMapper.selectById(tbProd.getProdId());
        if (prod == null){
            return Result.error().setMsg("商品不存在");
        }

        if (tbProd.getProdStatus() == 2){
            if (StringUtils.isEmpty(tbProd.getCheckReason())){
                return Result.error().setMsg("请输入审核不通过驳回");
            }
        }

        String token = request.getHeader("token");
        if (token == null){
            return Result.error().setMsg("审核前请先登录");
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);

        prod.setCheckId(userId);
        prod.setCheckStatus(tbProd.getCheckStatus());
        prod.setCheckReason(tbProd.getCheckReason());
        //如果审核通过，设置商品的上线状态
        if (tbProd.getCheckStatus() == 1){
            prod.setProdStatus(1);
        }
        tbProdMapper.updateById(prod);

        String message = JSON.toJSONString(prod);
        kafkaTemplate.send("topic-prod",message);

        return Result.ok();
    }

    @Override
    public Result getProdListFromEs(ProdPageVo prodPageVo) {
        Integer pageNum = 0;
        if (prodPageVo.getPageNum() > 0){
            pageNum = prodPageVo.getPageNum() - 1;
        }

        PageRequest pageRequest = PageRequest.of(pageNum, prodPageVo.getPageSize());

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.matchAllQuery());

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withPageable(pageRequest).withQuery(boolQueryBuilder);
        SearchHits<TbProd> searchHits = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), TbProd.class);

        long total = searchHits.getTotalHits();
        ArrayList<Object> records = new ArrayList<>();

        for (SearchHit<TbProd> searchHit : searchHits.getSearchHits()) {
            TbProd tbProd = searchHit.getContent();

            records.add(tbProd);
        }

        HashMap<String, Object> map = new HashMap<>(1);
        map.put("total",total);
        map.put("records",records);

        return Result.ok().setData(map);
    }

    /**
     * 接收Kafka消息（商品审核消息）
     * @param message
     * @param acknowledgment
     */
    @KafkaListener(topics = "topic-prod")
    public void recvProdMessage(String message, Acknowledgment acknowledgment){
        log.info("接收到消息：{}",message);
        TbProd tbProd = JSON.parseObject(message, TbProd.class);
        if (tbProd.getCheckStatus() == 2){
            try {
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

                messageHelper.setTo("393045387@qq.com");
                messageHelper.setFrom("393045387@qq.com");
                messageHelper.setSubject("商品审核结果通知");

                String body = "商品审核被驳回：" + tbProd.getCheckReason();
                messageHelper.setText(body);

                javaMailSender.send(mimeMessage);
            } catch (MessagingException e) {
//                throw new RuntimeException(e);
                e.printStackTrace();
            }
        }

        if (tbProd.getCheckStatus() == 1){
            String body = "商品审核通过:" + tbProd.getProdName();
            MobileMessageUtil.sendMobileMessage("15735805916",body);
            System.out.println("发送短信成功");

            //同步商品到ES中
            IndexOperations indexOps = elasticsearchRestTemplate.indexOps(TbProd.class);
            boolean exists = indexOps.exists();
            if (!exists){
                //创建索引
                indexOps.create();

                //创建映射
                Document mapping = indexOps.createMapping();
                indexOps.putMapping(mapping);
            }

            TbProd prod = tbProdMapper.getProdByid(tbProd.getProdId());
            elasticsearchRestTemplate.save(prod);
        }
        acknowledgment.acknowledge();
        System.out.println("确认消息：商品审核消息~~~~~~~~~~~~~~~~~~~~~~~~~~");

    }
}




